import { ZkpAddEmits, ZkpAddProps } from "./prop"
import { getJgZkpXm, addZkp, MAGIC_SUCC_CODE } from "@api"
import { EventSure } from "@ui/utils/var"
import { SetupContext } from "vue"
export function use(props: ZkpAddProps, emit: SetupContext<ZkpAddEmits>['emit']) {
  const formData = ref<LisZkpItem>({ yqid: '', ph: '', zkspdm: '', id: '' }),
    tableData = ref<any[]>([]),
    addShow = ref(false),
    currentRow = ref(),
    formTable = ref(),
    addModule = ref()
  watch(() => props.data, cancel)
  function add() {
    if (formData.value.yqid)
      addShow.value = true
    else
      ElMessage({ type: 'warning', message: '请录入质控品信息' })
  }
  function setFormData(data: any) {
    tableData.value = data
    nextTick(() => {
      if (formTable.value) {
        formTable.value.layout()
      }
    })
  }
  function sure(data: any[]) {
    const filter = data.filter((it) => {
      return tableData.value.filter(cs => {
        return cs.zbid == it.zbid
      }).length
    })
    if (filter.length) {
      ElMessage({ type: 'warning', message: '以下数据：【' + filter.map(it => it.zbmc).join('】,【') + '】重复出现，请重新选择' })
      return
    }
    setFormData(tableData.value.concat(data || []))
    if (addModule.value)
      addModule.value.clear()
    addShow.value = false
  }
  function del() {
    const obj = currentRow.value
    if (obj) {
      const { zbid } = obj
      setFormData(tableData.value.filter(it => it.zbid != zbid))
    } else {
      ElMessage({ type: 'warning', message: '请选择要删除的项目' })
    }
  }
  function cancel() {
    formData.value = { ...props.data } as LisZkpItem
    if (formData.value.id) {
      getJgZkpXm({ yqid: formData.value.yqid, zkpid: formData.value.id }).then(({ data: { list } }) => {
        tableData.value = list
      })
    } else {
      tableData.value = []
    }
  }
  function save() {
    addZkp({ ...formData.value, data: tableData.value }).then(({ code, data, message }) => {
      console.log(code, MAGIC_SUCC_CODE, data, message)
      if (code === MAGIC_SUCC_CODE) {
        emit(EventSure)
        ElMessage({ type: 'success', message: '新增成功' })
      } else
        ElMessage({ type: 'warning', message })
    })
  }
  return { formData, tableData, cancel, add, addShow, sure, formTable, addModule, save, currentRow, del }
} 